package com.sss.simpleemps.servlet;

import com.sss.simpleemps.common.domain.Admin;
import com.sss.simpleemps.service.AdminService;
import com.sss.simpleemps.service.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    //web 层注入 服务层
    AdminService adminService=new AdminServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        Admin adminInDB=adminService.findAdminByName(userName);
        if(adminInDB==null){
            //用户不存在
            request.setAttribute("msg","用户名不存在");//把信息存在request对象中，页面就可以通过el表达式获取
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else {
            if(adminInDB.getPassword().equals(password)){
                //OK
                HttpSession session = request.getSession();
                session.setAttribute("admin",adminInDB);
                request.getRequestDispatcher("/home.jsp").forward(request,response);
            }else {
                //密码错误
                request.setAttribute("msg","密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
                }
        }
    }
}
